<template>
  <view class="user-manage-container">
    <!-- 搜索和筛选区域 -->
    <view class="filter-section">
      <view class="search-box">
        <uni-search-bar 
          placeholder="输入用户名/手机号搜索" 
          v-model="searchKeyword"
          @confirm="handleSearch"
          :cancel-button="none"
          clear-button="always"
        ></uni-search-bar>
      </view>
      <view class="filter-options">
        <picker @change="statusFilterChange" :value="filterStatus" :range="statusOptions">
          <view class="filter-item">
            {{ statusOptions[filterStatus] }}
            <uni-icons type="arrowdown" size="14" color="#666"></uni-icons>
          </view>
        </picker>
        <!-- <picker mode="date" @change="dateFilterChange">
          <view class="filter-item">
            注册时间
            <uni-icons type="calendar" size="14" color="#666"></uni-icons>
          </view>
        </picker> -->
      </view>
    </view>

    <!-- 用户列表 -->
    <scroll-view 
      class="user-list" 
      scroll-y 
      @scrolltolower="loadMore"
      :show-scrollbar="true"
    >
      <view v-if="userList.length === 0 && !loading" class="empty-tips">
        <uni-icons type="search" size="24" color="#999"></uni-icons>
        <text class="empty-text">暂无相关用户</text>
      </view>

      <view class="user-card" v-for="user in userList" :key="user.id">
        <view class="user-info">
          <image class="user-avatar" :src="user.avatar || defaultAvatar" mode="aspectFill"></image>
          <view class="user-details">
            <text class="username">{{ user.username || '未命名用户' }}</text>
            <view class="meta-info">
              <text class="user-id">ID: {{ user.id }}</text>
              <text class="mobile">手机: {{ user.mobile || '未绑定' }}</text>
            </view>
            <text class="register-time">注册时间: {{ formatDate(user.createTime) }}</text>
          </view>
        </view>
        <view class="status-section">
          <view class="user-status" :class="user.status">
            {{ user.status === "normal" ? "启用" : "禁用" }}
          </view>
          <view class="user-role">
            {{ roleMap[user.role] || '普通用户' }}
          </view>
        </view>
        <view class="user-actions">
          <button class="action-btn" 
            :class="user.status === 'normal' ? 'warning' : 'success'" 
            @tap="toggleUserStatus(user)">
            {{ user.status === 'normal' ? '禁用' : '启用' }}
          </button>
          <!-- <button class="action-btn primary" @tap="handleEdit(user)">编辑</button> -->
          <button 
            class="action-btn danger" 
            @tap="handleDelete(user)"
            v-if="adminInfo.role === '超级管理员'">
            删除
          </button>
        </view>
      </view>

      <uni-load-more 
        :status="loadingStatus" 
        :content-text="loadText"
        :icon-size="16"
      ></uni-load-more>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog 
        mode="input"
        title="编辑用户"
        @confirm="confirmEdit"
        @close="cancelEdit">
        <uni-forms :model="editForm" label-width="80">
          <uni-forms-item label="用户名" required>
            <uni-easyinput 
              v-model="editForm.username" 
              placeholder="请输入用户名"
              trim="both"
              :inputBorder="false"
            />
          </uni-forms-item>
          <uni-forms-item label="用户角色">
            <uni-data-checkbox 
              v-model="editForm.role" 
              :localdata="roles"
              :wrap="true"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      adminInfo: {
        role: "超级管理员"
      },
      searchKeyword: '',
      filterStatus: 0,
      statusOptions: ['全部状态', '正常', '已禁用'],
      statusMap: ['', 'normal', 'disabled'],
      roleMap: {
        user: '普通用户',
        vip: 'VIP用户',
        admin: '管理员'
      },
      filterDate: null,
      userList: [],
      loading: false,
      loadingStatus: 'more',
      defaultAvatar: '/static/avatar-default.png',
      editForm: {
        id: null,
        username: '',
        role: 'user'
      },
      roles: [
        { value: 'user', text: '普通用户' },
        { value: 'vip', text: 'VIP用户' },
        { value: 'admin', text: '管理员' }
      ],
      currentPage: 1,
      total: 0,
      pageSize: 10,
      loadText: {
        contentdown: '上拉加载更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      }
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    async handleDelete(user) {
      uni.showModal({
        title: '确认删除',
        content: `确定永久删除用户 ${user.username} 吗？`,
        confirmColor: '#DD524D',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...', mask: true })
              
              const res = await uniCloud.callFunction({
                name: 'deleteUser',
                data: { userId: user.id }
              })
    
              if (res.result.code === 0) {
                // 从列表中移除
                this.userList = this.userList.filter(u => u.id !== user.id)
                this.total--
                uni.showToast({ title: '删除成功' })
              } else {
                uni.showToast({ 
                  title: res.result.message || '删除失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('删除失败:', error)
              uni.showToast({ 
                title: error.message || '删除失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },
     async toggleUserStatus(user) {
          const newStatus = user.status === 'normal' ? 0 : 1
          const action = user.status === 'normal' ? '禁用' : '启用'
          
          uni.showLoading({ title: '操作中...', mask: true })
          try {
            await uniCloud.callFunction({
              name: 'updateUserStatus',
              data: {
                userId: user.id,
                status: newStatus
              }
            })
            
            user.status = newStatus === 1 ? 'normal' : 'disabled'
            uni.showToast({ title: `${action}成功` })
          } catch (error) {
            console.error(`${action}用户失败:`, error)
            uni.showToast({ title: `${action}失败`, icon: 'none' })
          } finally {
            uni.hideLoading()
          }
        },
    initData() {
      this.loadUsers(true)
    },

    formatDate(timestamp) {
      if (!timestamp) return '未知'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    async loadUsers(reset = false) {
      // if (this.loading || this.loadingStatus === 'noMore') return
      
      try {
        this.loading = true
        this.loadingStatus = 'loading'

        const params = {
          keyword: this.searchKeyword.trim(),
          status: this.statusMap[this.filterStatus],
          page: reset ? 1 : this.currentPage,
          pageSize: this.pageSize
        }
        console.log(params)
        // 添加日期筛选参数
        if (this.filterDate) {
          params.startTime = this.filterDate.startTime
          params.endTime = this.filterDate.endTime
        }

        const res = await uniCloud.callFunction({
          name: 'getUserList',
          data: params
        })

        if (res.result.code === 0) {
          const formattedList = res.result.data.list.map(user => ({
            id: user._id,
            username: user.username,
            avatar: user.avatar,
            mobile: user.mobile,
            status: user.status === 1 ? 'normal' : 'disabled',
            createTime: user.createTime,
            role: user.role || 'user'
          }))

          this.userList = reset ? formattedList : [...this.userList, ...formattedList]
          this.total = res.result.data.total
          
          this.loadingStatus = this.userList.length >= this.total ? 'noMore' : 'more'
          this.currentPage = reset ? 2 : this.currentPage + 1
        }
      } catch (error) {
        console.error('加载用户失败:', error)
        uni.showToast({
          title: '数据加载失败',
          icon: 'none',
          duration: 2000
        })
        this.loadingStatus = 'more'
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.userList = []
      this.loadUsers()
    },

    statusFilterChange(e) {
      this.filterStatus = e.detail.value
      console.log(this.filterStatus)
      this.currentPage = 1
      this.userList = []
      this.loadUsers()
    },

    dateFilterChange(e) {
      if (e.detail.value) {
        const selectedDate = new Date(e.detail.value)
        const startTime = new Date(
          selectedDate.getFullYear(),
          selectedDate.getMonth(),
          selectedDate.getDate()
        ).getTime()
        const endTime = startTime + 86400000 - 1
        this.filterDate = { startTime, endTime }
      } else {
        this.filterDate = null
      }
      this.currentPage = 1
      this.userList = []
      this.loadUsers()
    },

    loadMore() {
      if (this.loadingStatus !== 'noMore') {
        this.loadUsers()
      }
    },

    // 其他方法保持不变...
  }
}
</script>

<style lang="scss" scoped>
.user-manage-container {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.filter-section {
  background: #ffffff;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .search-box {
    margin-bottom: 24rpx;
  }

  .filter-options {
    display: flex;
    gap: 24rpx;

    .filter-item {
      flex: 1;
      padding: 16rpx 24rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #606266;
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all 0.2s;

      &:active {
        background-color: #f1f3f5;
      }
    }
  }
}

.user-list {
  height: calc(100vh - 240rpx);
  padding-bottom: env(safe-area-inset-bottom);
}

.empty-tips {
  text-align: center;
  padding: 80rpx 0;
  color: #909399;

  .empty-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
  }
}

.user-card {
  background: #ffffff;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);

  .user-info {
    display: flex;
    align-items: flex-start;
    margin-bottom: 24rpx;

    .user-avatar {
      width: 96rpx;
      height: 96rpx;
      border-radius: 50%;
      margin-right: 24rpx;
      background-color: #f8f9fa;
    }

    .user-details {
      flex: 1;

      .username {
        font-size: 32rpx;
        font-weight: 500;
        color: #1a1a1a;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }

      .meta-info {
        display: flex;
        gap: 24rpx;
        margin-bottom: 12rpx;

        .user-id, .mobile {
          font-size: 24rpx;
          color: #666;
        }
      }

      .register-time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .status-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .user-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 8rpx;

      &.normal {
        background: #e8f5e9;
        color: #2e7d32;
      }

      &.disabled {
        background: #ffebee;
        color: #c62828;
      }
    }

    .user-role {
      font-size: 24rpx;
      color: #666;
      padding: 8rpx 16rpx;
      background: #f0f2f5;
      border-radius: 8rpx;
    }
  }

  .user-actions {
    display: flex;
    gap: 16rpx;
    justify-content: flex-end;

    .action-btn {
      padding: 12rpx 32rpx;
      font-size: 26rpx;
      border-radius: 8rpx;
      line-height: 1.4;
      transition: all 0.2s;

      &:active {
        opacity: 0.8;
        transform: scale(0.98);
      }

      &.primary {
        background-color: #007aff;
        color: #ffffff;
      }

      &.warning {
        background-color: #ff9500;
        color: #ffffff;
      }

      &.success {
        background-color: #34c759;
        color: #ffffff;
      }

      &.danger {
        background-color: #ff3b30;
        color: #ffffff;
      }
    }
  }
}
</style>